$package('common.config.customFilter');
$import('basics.tableOpt');
$import('common.config.category.serviceDirectoryUtils');
$import('common.config.category.serviceCatalog');
/**  
 * @author mars  
 * @constructor mars
 * @description 过滤器表达式函数
 * @date 2011-09-06
 * @since version 1.0 
 */
common.config.customFilter.filterCM = function(){
		return {
				/**
				 * 取得option HTML
				 * @param options 值对应的key 
				 */
				getOptionsHTML_i18n:function(options) {
				    var optionHTML = '';
				    $.each(options, function(k,v) {
				    	if("time"==v){
				    		v="common_createTime";
				    	}
				    	optionHTML += '<option value="'+k+'" id="'+v+'">'+i18n[v]+'</option>';
				    });
				    return optionHTML;
				},
				/**
				 * 加载条件HTML
				 * @param options 值对应的key 
				 */
				loadConditionHTML:function(options){
					return common.config.customFilter.filterCM.getOptionsHTML_i18n(options);
				},
				/**
				 * 加载查询方式(包含、不包含)html
				 *
				 */
				loadOperatorByString:function(){
					var options = {
								'like' : 'label_sla_matches',
								'not like' : 'label_sla_notMatches'
						};
					return common.config.customFilter.filterCM.getOptionsHTML_i18n(options);
				},
				/**
				 * 加载查询方式（等于、不等）html
				 */
				loadOperatorByRelating:function(){
					var options = {
							'=':'label_sla_eq',
							'!=':'label_sla_notEq'
						};
					return common.config.customFilter.filterCM.getOptionsHTML_i18n(options);
				},
				/**
				 * 加载查询方式（等于、不等）html
				 */
				loadOperatorByMatches:function(){
					var options = {
							'=':'label_sla_matches',
							'!=' : 'label_sla_notMatches'
						};
					return common.config.customFilter.filterCM.getOptionsHTML_i18n(options);
				},
				/**
				 * 加载查询方式（包含于、不包含）html
				 */
				loadOperatorByCompanyNoMatches:function(){
					var options = {
							'in':'label_sla_matches',
							'not in' : 'label_sla_notMatches'
						};
					return common.config.customFilter.filterCM.getOptionsHTML_i18n(options);
				},
				/**
				 * 加载查询方式（大于、大于等于、等于、小于、小于等于）html
				 */
				loadOperatorByNumberAndData:function(){
					var options = {
							'>=':'lable_filter_egt',
							'>':'lable_filter_gt',
							'=':'label_sla_eq',
							'<':'lable_filter_lt',
							'<=':'lable_filter_elt'
					};
					return common.config.customFilter.filterCM.getOptionsHTML_i18n(options);
				},
				/**
				 * 组合表达式HTML
				 * @param valueID 值Id
				 * @param appendID 添加到该元素之后
				 */
				setExpOperation:function(valueID,appendID){
					var tp=$(valueID).val().substring($(valueID).val().lastIndexOf('_')+1);
					$(appendID).empty();
					if(tp=="Long"||tp=="Data"||tp=="Date"||tp=="Double"||tp=="Int"||tp=="Intger"){
						$(common.config.customFilter.filterCM.loadOperatorByNumberAndData()).appendTo(appendID);
					}else if(tp=="String" ||tp.indexOf("Radio")>-1||tp.indexOf("Checkbox")>-1){
						$(common.config.customFilter.filterCM.loadOperatorByString()).appendTo(appendID); 	
					}else if($(valueID).val()=="serviceDirectoryItem.subServiceId_subServiceId"||$(valueID).val()=='requestServiceDir'){
						$(common.config.customFilter.filterCM.loadOperatorByMatches()).appendTo(appendID); 	
					}else if($(valueID).val()=="companyNo_companyNo"){
						$(common.config.customFilter.filterCM.loadOperatorByCompanyNoMatches()).appendTo(appendID);
					}else{
						$(common.config.customFilter.filterCM.loadOperatorByRelating()).appendTo(appendID);
					}
				},
				/**
				 * 解析值的类型
				 * @param valueID 值元素
				 */
				switchExpressPropType:function(valueID){
					var sel=$(valueID).val();
					//如果是配置项的部门
					if(sel.indexOf("department")>-1){
						return "String";
					}
					if(sel.indexOf("createdBy.orgnization.orgNo")>-1||sel.indexOf("location")>-1){//请求人所在组和所在位置
						return "Long";
					}
		    		sel=sel.substring(sel.lastIndexOf('_')+1,sel.length);
					if(sel=="String"||sel=="loginName"||sel=="createdBy.loginName" ){
						return "String";
					}else if(sel=="orgNo"||sel=="Long"||sel=="dcode"||sel.indexOf("eventId")>-1||sel.indexOf("companyNo")>-1
							||sel.indexOf("subServiceId")>-1||sel.indexOf("singleServiceId")>-1 ||sel.indexOf("DataDictionaray")>-1){
						return "Long";
					}else if(sel=="Data" || sel=="Date"){
						return "Data";
					}else if(sel=="Double"){
						return "Double";
					}else if(sel=="Int"){
						return "Int";
					}else if(sel=="Boolean"){
						return "Boolean";
					}else if(sel=="knownError"){
						return "Long";
					}else 
						return "String";
				},
				/**
				 * 选择分类.
				 * @param putID ID元素
				 * @param putName name元素
				 * @param flag 类型标识
				 */
				selectCategory:function(putID,putName,flag){
					if(flag.indexOf("ReventId")>-1){
						common.config.category.eventCategoryTree.requestCategory(putName,putID);
					}else if(flag.indexOf("PeventId")>-1){
						common.config.category.eventCategoryTree.problemCategory(putName,putID);
					}else if(flag.indexOf("CeventId")>-1){
						common.config.category.eventCategoryTree.changeCategory(putName,putID);
					}else if(flag.indexOf("CIeventId")>-1){
						var ci_categoryNo=putID.substring(1,putID.length);
						var ci_categoryName=putName.substring(1,putName.length);
						itsm.cim.ciCategoryTree.configureItemTree('search_ciCategoryTreeDiv','search_ciCategoryTreeTree',ci_categoryNo,ci_categoryName,'false',function(){});
					}else if(flag.indexOf("KeventId")>-1){
						common.knowledge.knowledgeTree.selectKnowledgeCategory('#knowledge_category_select_window','#knowledge_category_select_tree',putName,putID);
					}
				},
				/**
				 * 添加表达式列表.
				 */
				replaceExpressStr:function(){
					
					var _id = 'id_'+new Date().getTime();
					var str= '<tr id="constraint{0}">'+
					    '<td style="background-color:#FFF;height:28px;text-align:center">{1}'+
					    //'<input type="hidden" name="rule_condition_constraints_conNo" value="{2}"/>'+
					    '<input type="hidden" name="express_propType" value="{2}" >'+
					    '<input type="hidden" name="express_propDisplayName" value="{3}" >'+
					    '<input type="hidden" name="express_propName" value="{4}" readonly>'+
					    '</td>'+
					    '<td style="background-color:#FFF;text-align:center">{5}'+
					    '<input type="hidden" name="express_displayOperator" value="{6}">'+
					    '<input type="hidden" name="express_operator" value="{7}">'+
					    '</td>'+
					    '<td style="background-color:#FFF;text-align:center">{10}'+
					    '<input type="hidden" name="express_propertyDisplayValue" value="{11}">'+
					    '<input type="hidden" name="express_propertyValue" value="{12}">'+
					    '</td>'+
					    '<td style="background-color:#FFF;text-align:center"><select name="express_joinType">{8}</select>'+
					    '</td>'+
					    '<td style="background-color:#FFF;text-align:center">'+
					    '<img src="../images/icons/delete.gif" style="cursor:pointer" onclick="common.config.customFilter.filterCM.removeRow(\'#'+_id+'\')"/>'+
					    '<img id="'+_id+'" src="../images/icons/arrow_up_blue.gif" style="cursor:pointer" onclick="basics.tableOpt.trUp(\'#'+_id+'\')"/>'+
					    '<img src="../images/icons/arrow_down_blue.gif" style="cursor:pointer" onclick="basics.tableOpt.trDown(\'#customFilter_constraintsTable\',\'#'+_id+'\')"/>'+
					    '</td>'+
					  '</tr>';
					  for (var i=0; i<arguments.length; i++) {
						  
						  str = str.replace('{'+i+'}', arguments[i]);
					  }
					  return str;
				},
				/**
				 * 判断是否有服务目录条件，有则显示扩展字段
				 */
				judgeAttr:function(){
					$(".express_attr").remove();
					var bool=false;
					$("input[type=hidden][name=express_propName]").each(function(i,event){
						var categoryId=$("input[type=hidden][name=express_propertyValue]:eq("+i+")").val();
						//console.log($(this).val());
					    if($(this).val()=="serviceDirectory.eventId"){//仅判断请求模块
					    	//$("#express_attrName").show();
					    	$.post('event!findByIdCategorys.action','categoryId='+categoryId,function(cat){
					    		if(cat.formId!==0){
					    			var _param = {"formCustomId" : cat.formId};
									$.post('formCustom!findFormCustomById.action',_param,function(data){
										if(data.formCustomContents!=""){
											common.config.customFilter.filterCM.optionHtml(data.formCustomContents,"#express_propName");
										}
									});
					    		}
					    	});
					    	bool=true;
					    }else if($(this).val()=="category.cno"){//仅判断配置项模块
					    	$.post('ciCategory!findCICategoryById.action','categoryNo='+categoryId,function(data){
					    		if(data!=null && data.categoryType!=null){
									if(!isNaN(data.categoryType)){
										$.post('ci!attributeList.action','eavNo='+data.categoryType,function(attr){
											if(attr!=null && attr.length>0){
												for(var i=0;i<attr.length;i++){
													var event=attr[i];
													if(event.attrName.indexOf("eav_")>-1){
														$('#express_propName').append('<option class="express_attr" id="'+event.attrAsName+'" attrdataDictionary="'+event.attrdataDictionary+'" value="'+event.attrName+'_'+event.attrType+'">'+event.attrAsName+'</option>');
													}
												}
											}
										});
									}
					    		}
					    		
					    	});
					    	bool=true;
					    }
					    	
					});
					if(!bool){
						$(".express_attr").remove();
					}
				},
				/**
				 * 解析出扩展字段
				 */
				optionHtml:function(attrJson,selectId){
					if(attrJson && attrJson!==''){
						attrJson=JSON.parse(common.security.base64Util.decode(attrJson));
						//var mark=false;//记录是否需要插入空白字段
						//var column=0;
						for ( var i = 0; i < attrJson.length; i++) {
							var event=attrJson[i];
							if(event.attrName.indexOf(".attrVals")>0){
								$(selectId).append('<option class="express_attr" id="'+event.label+'" attrdataDictionary="'+event.attrdataDictionary+'" value="'+event.attrName+'_'+event.attrType+'">'+event.label+'</option>');
							}
						}
					}
				},
				/**
				 * 移除表格行.
				 * @param rowId 行Id
				 */
				removeRow:function(rowId){
					var tip='';//express_propName serviceDirectory.eventId
					var exPropName=$(rowId).parent().parent().find(":hidden[name='express_propName']:eq(0)").val();
					if(exPropName.indexOf("serviceDirectory.eventId")>-1 || exPropName.indexOf("category.cno")>-1)
						tip=i18n.label_delServiceDirectory+'<br/>';
					msgConfirm(i18n['msg_msg'],tip+'<br/>'+i18n['msg_confirmDelete'],function(){
						basics.tableOpt.trDel(rowId);
						$('.lineTableBgDiv').css({"height":""}).css({"height":"auto"});
						common.config.customFilter.filterCM.judgeAttr();
						$("input[type=hidden][name=express_propName]").each(function(i,event){
						    if($(this).val().indexOf('eav_')>-1){//仅判断请求模块
						    	$(this).parent().parent().remove();
						    }
						});
					});
				},
				/**
				 * 创建变量值的事件.
				 * @param flag 类型标识
				 * @param htmlPut Html元素
				 * @param nameId Name元素
				 * @param valueId Id元素
				 * @param method 回调方法
				 *     services.msc
				 */
				createPVEvent:function(flag,htmlPut,nameId,valueId,method){
					var HTML="";
					var _valueId='#'+valueId;
					$('#express_propValueDIV').show();
					$('#propValue_ToDataDIV').hide();
					if(flag.indexOf("singleServiceId")>-1){//服务目录单选
						HTML="<input id="+nameId+" style='width:96%;cursor:pointer;color:#555555' onclick=common.config.category.serviceCatalog.selectSingleServiceDir('#"+nameId+"','#"+valueId+"') readonly/><input type='hidden' id='"+valueId+"' />";
					}
					else if(flag.indexOf("eventId")>-1){
						HTML="<input id="+nameId+" style='width:96%;cursor:pointer;color:#555555' onclick=common.config.customFilter.filterCM.selectCategory('#"+valueId+"','#"+nameId+"','"+flag+"') readonly/><input type='hidden' id='"+valueId+"' />";
					}else if(flag.indexOf("location")>-1){
						HTML="<input id="+nameId+" style='width:96%;cursor:pointer;color:#555555' onclick=common.config.category.eventCategoryTree.selectlocation('#"+nameId+"','#"+valueId+"') readonly/><input type='hidden' id='"+valueId+"' />";
					}else if(flag.indexOf("dcode")>-1 || flag.indexOf("DataDictionaray")>-1){
						HTML="<select id='"+valueId+"' style='width:96%'></select>";
						if(flag.indexOf('requestDTO')>-1){
							flag=$('#express_propName').find("option:selected").attr('attrdataDictionary');
						}else{
							flag=flag.substring(0,flag.indexOf("."));
							if(flag=='slaState'){				
								flag='SLAStatus';
							}
						}
						common.config.dictionary.dataDictionaryUtil.loadOptionsByCode(flag,_valueId);
					}else if(flag.indexOf("loginName")>-1 ){
						var showNameType='filter_fullName';
						if(flag=="userName_loginName" || flag=="owner_loginName" || flag=="originalUser_loginName"){
							showNameType="ci_fullName";
						}
						HTML="<input id='"+nameId+"' style='width:96%;cursor:pointer;color:#555555' onclick=common.security.userUtil.selectUser('#"+nameId+"','#"+valueId+"','','"+showNameType+"','"+companyNo+"') readonly/><input type='hidden' id='"+valueId+"' />";
					}else if(flag.indexOf("orgNo")>-1){
						//如果是配置项的部门
						if(flag.indexOf("department")>-1){
							HTML="<input id="+valueId+" style='width:96%;cursor:pointer;color:#555555' onclick=common.security.organizationTreeUtil.selectORG('#"+valueId+"','','"+companyNo+"') readonly/>";
						}else{
							HTML="<input id="+nameId+" style='width:96%;cursor:pointer;color:#555555' onclick=common.security.organizationTreeUtil.selectORG('#"+nameId+"','#"+valueId+"','"+companyNo+"') readonly/><input type='hidden' id='"+valueId+"' />";
						}	
					}else if(flag.indexOf("Data")>-1 || flag.indexOf("Date")>-1){
						$('#express_propertyValue').val("");
						$('#express_propValueDIV').hide();
						$('#propValue_ToDataDIV').show();
						setTimeout(function(){
							DateBox97("#express_propertyValue");
						},100);
					}else if(flag.indexOf("financeCorrespond")>-1){
						HTML="<input  name='"+valueId+"' type='radio'  id='fimappingYes' checked/>"+i18n['label_basicConfig_deafultCurrencyYes']+"<input  name='"+valueId+"' type='radio'  id='fimappingNo' />"+i18n['label_basicConfig_deafultCurrencyNo'];
					}else if(flag.indexOf("companyNo")>-1){
						HTML="<input id="+nameId+" style='width:96%;cursor:pointer;color:#555555' onclick=itsm.itsop.selectCompany.openSelectCompanyWinCheckbox('#"+valueId+"','#"+nameId+"','','loginName','-1') readonly/><input type='hidden' id='"+valueId+"' />";
						$('#selectCompany_grid_select').unbind().click(common.config.customFilter.filterCM.clickCommon);
						$('#selectCompany_grid_select_User').unbind().click(common.config.customFilter.filterCM.clickCommonUser);
					}else if(flag.indexOf("subServiceId")>-1||flag.indexOf("ServiceDir")>-1){
						HTML="<input id="+nameId+" style='width:96%;cursor:pointer;color:#555555' onclick=common.config.category.serviceCatalog.selectSingleServiceDir('#"+nameId+"','#"+valueId+"') readonly/><input type='hidden' id='"+valueId+"' />";
					}else if(flag.indexOf("knownError_knownError")>-1){
						HTML="<input checked type='radio' name='knownError_radio' onclick=common.config.customFilter.filterCM.setKnownError('1','#"+nameId+"','#"+valueId+"') value='1'/>"+i18n['label_dynamicReports_yes']+"<input type='radio' name='knownError_radio' onclick=common.config.customFilter.filterCM.setKnownError('0','#"+nameId+"','#"+valueId+"') value='0'/>"+i18n['label_dynamicReports_no']+"<input type='hidden' id="+nameId+" value='1'/><input type='hidden' id='"+valueId+"' value='1'/>";
					}else if(flag.indexOf("knowledgeStatus_String")!=-1){
						HTML='<select id="'+valueId+'">';
						HTML+='<option value="">--'+i18n['pleaseSelect']+'--</option>'; 
						HTML+='<option value="0">'+i18n['knowledge_satus_approving']+'</option>';
						HTML+='<option value="1">'+i18n['knowledge_satus_normal']+'</option>';
						HTML+='<option value="-1">'+i18n['title_refused']+'</option>';
						HTML+='</select>';
					}else if(flag.indexOf('Int')>-1 || flag.indexOf('assetsOriginalValue_Double')>-1){
						HTML="<input class='easyui-numberbox' id="+valueId+" style='width:96%;color:#555555'/>";
					}else{
						HTML="<input style='width:96%' id='"+valueId+"' />";
					}
					$(htmlPut).html(HTML);
					if(flag.indexOf('Int')>-1 || flag.indexOf('assetsOriginalValue_Double')>-1){
						$('#'+valueId).numberbox({
							min:0,
							max:999999999
						});
					}
				},
				/**
				 * 设置已知知识的表达式
				 * @param value 值
				 * @param nameId name元素
				 * @param valueId 值元素
				 */
				setKnownError:function(value,nameId,valueId){
					$(nameId+','+valueId).val(value);
				},
				/**
				 * @description 确认选择
				 */
				clickCommon:function(){
					var strs= new Array(); //定义一数组
					var rowIds="";
					var rowValue="";
					rowIds= $("#selectCompanySLA_grid").getGridParam('selarrrow')+"";
					if(rowIds.length>0){
						strs=rowIds.split(",");
						for (i=0;i<strs.length ;i++ ) {
							var rowData=$("#selectCompanySLA_grid").getRowData(strs[i]);
							rowValue+=rowData.orgName+",";
						}
						rowValue=rowValue.substring(0,rowValue.length-1);
						$('#express_propertyValue').val(rowIds);
						$('#express_propertyName').val(rowValue);
					}
					$('#selectCompanyDiv').dialog('close');
				},
				/**
				 * @description 确认选择
				 */
				clickCommonUser:function(){
					$('#express_propertyValue').val(companyNo);
					$('#express_propertyName').val(companyName);
					$('#selectCompanyDiv').dialog('close');
				},
				/**
				 * 获取显示值.
				 * @param flagId 类型Id
				 * @param nameId name元素
				 * @param valueId 值元素
				 */
				getPvalue:function(flagId,valueId,nameId){
					var flag=$(flagId).val();
					if(flag.indexOf("dcode")>-1 || flag.indexOf("knowledgeStatus")>-1 || flag.indexOf("DataDictionaray")>-1) {
						return $(valueId).find("option:selected").text();
					}
					if(flag.indexOf("Boolean")>-1||flag.indexOf("Int")>-1||flag.indexOf("Integer")>-1||flag.indexOf("Lob")>-1
							||flag.indexOf("Radio")>-1||flag.indexOf("Integer")>-1||flag.indexOf("Checkbox")>-1
							||flag.indexOf("String")>-1||flag.indexOf("Data")>-1||flag.indexOf("Date")>-1||flag.indexOf("Long")>-1||flag.indexOf("Double")>-1){
						return $(valueId).val();					
					}
					if(flag.indexOf("orgNo")>-1||flag.indexOf("eventId")>-1 || flag.indexOf("companyNo")>-1|| flag.indexOf("subServiceId")>-1|| flag.indexOf("singleServiceId")>-1||flag.indexOf("loginName")>-1||flag.indexOf("location")>-1 ||flag.indexOf("ServiceDir")>-1 ){
						if(flag.indexOf("department")>-1){
							return $(valueId).val();
						}
						return $(nameId).val();
					}
					if(flag.indexOf("knownError_knownError")>-1){
						return $(valueId).val()=='1'?i18n['label_dynamicReports_yes']:i18n['label_dynamicReports_no'];
					}
				},
				/**
				 * 获取表达式列表集合.
				 * @param filterDIV  过滤器DIV
				 * @param expressDIV 表达式DIV
				 * @param userName 创建用户登录名
				 * @param filterCategory 过滤器类别
				 * @param entityClass 实体class
				 */
				getFilterInfo:function(filterDIV,expressDIV,userName,filterCategory,entityClass){
					var filter = $(filterDIV+' form').getForm();
					$.extend(filter,{'customFilterDTO.userName':userName,'customFilterDTO.filterCategory':filterCategory,'customFilterDTO.entityClass':entityClass});
					var expressions = {};
					var propDisplay=$(expressDIV+' tbody input[name="express_propDisplayName"]');
					var propName = $(expressDIV+' tbody input[name="express_propName"]');
					var propType = $(expressDIV+' tbody input[name="express_propType"]');
					var displayOperator = $(expressDIV+' tbody input[name="express_displayOperator"]');
					var operator = $(expressDIV+' tbody input[name="express_operator"]');
					var joinType = $(expressDIV+' tbody select[name="express_joinType"]');
					var propValue = $(expressDIV+' tbody input[name="express_propertyValue"]');
					var propDisplayValue= $(expressDIV+' tbody input[name="express_propertyDisplayValue"]');
					for (i =0; i<propName.length; i++) {
						//expressions['customFilterDTO.expressions['+i+'].conNo'] = constraintsNos[i].value;
						expressions['customFilterDTO.expressions['+i+'].propDisplayName'] =propDisplay[i].value;
						//如果是状态
						if(propName[i].value.indexOf("Status")>-1 && propName[i].value.indexOf("knowledgeStatus")==-1){
							expressions['customFilterDTO.expressions['+i+'].propName'] ="status.dcode";
						}else if(propName[i].value.indexOf("supplier")>-1){//如果是产品供应商
							expressions['customFilterDTO.expressions['+i+'].propName'] ="provider.dcode";
						}else if(propName[i].value.indexOf("location")>-1){//如果是位置
							if(propName[i].value=='location.eventNames'){
								expressions['customFilterDTO.expressions['+i+'].propName'] ="location.eventId";
							}else{
								expressions['customFilterDTO.expressions['+i+'].propName'] ="loc.eventId";	
							}
						}else{
							expressions['customFilterDTO.expressions['+i+'].propName'] =propName[i].value;
						}
						expressions['customFilterDTO.expressions['+i+'].propType'] =propType[i].value;
						expressions['customFilterDTO.expressions['+i+'].displayOperator'] =displayOperator[i].value;
						expressions['customFilterDTO.expressions['+i+'].operator'] =operator[i].value;			
						expressions['customFilterDTO.expressions['+i+'].joinType'] =joinType[i].value;
						expressions['customFilterDTO.expressions['+i+'].propValue'] =propValue[i].value;
						expressions['customFilterDTO.expressions['+i+'].propDisplayValue'] =propDisplayValue[i].value;
					}
					$.extend(filter, expressions);
					return filter;
				}
		};
}();